package auth

import (
	"os"
	"time"
)

// Config JWT配置结构
type Config struct {
	SecretKey     string
	TokenDuration time.Duration
	RefreshDuration time.Duration
}

// DefaultConfig 默认JWT配置
func DefaultConfig() *Config {
	return &Config{
		SecretKey:       getEnvOrDefault("JWT_SECRET_KEY", "your-secret-key-change-in-production"),
		TokenDuration:   24 * time.Hour,
		RefreshDuration: 7 * 24 * time.Hour,
	}
}

// NewConfig 创建新的JWT配置
func NewConfig(secretKey string, tokenDuration, refreshDuration time.Duration) *Config {
	return &Config{
		SecretKey:       secretKey,
		TokenDuration:   tokenDuration,
		RefreshDuration: refreshDuration,
	}
}

// getEnvOrDefault 获取环境变量或返回默认值
func getEnvOrDefault(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// LoadConfigFromEnv 从环境变量加载配置
func LoadConfigFromEnv() *Config {
	config := DefaultConfig()
	
	// 从环境变量读取token持续时间
	if tokenDurationStr := os.Getenv("JWT_TOKEN_DURATION"); tokenDurationStr != "" {
		if duration, err := time.ParseDuration(tokenDurationStr); err == nil {
			config.TokenDuration = duration
		}
	}
	
	// 从环境变量读取refresh token持续时间
	if refreshDurationStr := os.Getenv("JWT_REFRESH_DURATION"); refreshDurationStr != "" {
		if duration, err := time.ParseDuration(refreshDurationStr); err == nil {
			config.RefreshDuration = duration
		}
	}
	
	return config
}